package com.hzeport.bgs22emduty.xxljob;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.dto.*;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.entity.DutyScheduleInfo;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.*;
import com.masa.common.core.base.BaseEntity;
import com.sun.xml.bind.v2.runtime.output.SAXOutput;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author zhangyangyang
 * @description
 * @date 2023/11/28 10:18
 */

@Slf4j
@Component
public class HbXxJob {


    @Resource
    private ScreenDutyMapsRepository screenDutyMapsRepository;

    @Resource
    private ScreenDutyMessageRepository screenDutyMessageRepository;

    @Resource
    private ScreenDutyExperienceRepository screenDutyExperienceRepository;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private SystemConfig systemConfig;
    @Resource
    private DutySignInfoRepository dutySignInfoRepository;
    @Resource
    private ScreenDutyLogRepository screenDutyLogRepository;
    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;

    @XxlJob("getHBData")
    public ReturnT<String> getHBData(String param) {
        try {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.now().withHour( 0 ).withMinute( 0 ).withSecond( 0 ).withNano( 0 );
            //获取所有海关编码
            List<ScreenDutyMaps> customCodes = screenDutyMapsRepository.list().stream().filter( i ->
                    !StringUtils.isEmpty(i.getCustomNo()) &&
                    !StringUtils.isEmpty(i.getHbUrl()) &&
                    !StringUtils.isEmpty(i.getLsUrl())
            ).collect(Collectors.toList());
            //把总署的信息添加进去
            ScreenDutyMaps zsScreenDutyMaps = new ScreenDutyMaps();
            zsScreenDutyMaps.setCustomNo(systemConfig.getZsCustomNo());
            zsScreenDutyMaps.setCustomCode(systemConfig.getZsCustomId());
            zsScreenDutyMaps.setCustomName(systemConfig.getZsCustomName());
            zsScreenDutyMaps.setHbUrl(systemConfig.getZsHbUrl());
            zsScreenDutyMaps.setLsUrl(systemConfig.getZsLsUrl());
            customCodes.add(zsScreenDutyMaps);
            List<ScreenDutyExperience> screenDutyExperiences = new ArrayList<>();
            List<ScreenDutyMessage> screenDutyMessages = new ArrayList<>();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            for (ScreenDutyMaps screenDutyMaps : customCodes) {
                List< ScreenDutyMessage > dutyMessages = screenDutyMessageRepository.list( new LambdaQueryWrapper< ScreenDutyMessage >()
                        .eq( ScreenDutyMessage::getCustomId , screenDutyMaps.getCustomCode() )
                        .ge( BaseEntity::getCreateTime , LocalDateTime.now().withHour( 0 ).withMinute( 0 ).withSecond( 0 ) )
                        .le( BaseEntity::getCreateTime , LocalDateTime.now().withHour( 23 ).withMinute( 59 ).withSecond( 59 ) )
                );
                List< String > dutyMessagesTitles = dutyMessages.stream().map( ScreenDutyMessage::getHbId ).collect( Collectors.toList() );

                List< ScreenDutyExperience > dutyExperiences = screenDutyExperienceRepository.list( new LambdaQueryWrapper< ScreenDutyExperience >()
                        .eq( ScreenDutyExperience::getCustomId , screenDutyMaps.getCustomCode() )
                        .ge( BaseEntity::getCreateTime , LocalDateTime.now().withHour( 0 ).withMinute( 0 ).withSecond( 0 ) )
                        .le( BaseEntity::getCreateTime , LocalDateTime.now().withHour( 23 ).withMinute( 59 ).withSecond( 59 ) )
                );
                List< String > dutyExperiencesTitles = dutyExperiences.stream().map( ScreenDutyExperience::getHbId ).collect( Collectors.toList() );
                //值班工作经验
                HbDto hbDtoExperience = new HbDto();
                hbDtoExperience.setCustomsCode(screenDutyMaps.getCustomNo());
                hbDtoExperience.setMediaTypeName("海关值班工作");
                hbDtoExperience.setSendTime(timeFormatter.format(localDateTime));
                HttpEntity<HbDto> entityExperience = new HttpEntity<>(hbDtoExperience, headers);
                log.info("进行接口调用地址"+screenDutyMaps.getHbUrl());
                log.info("进行接口调用参数"+entityExperience);
                ResponseEntity<String> experienceResponse = restTemplate.exchange(screenDutyMaps.getHbUrl(),
                        HttpMethod.POST, entityExperience, String.class);
                log.info("进行接口调用返回"+experienceResponse);
                //将json转为对象
                String experienceJson = experienceResponse.getBody();
                JSONArray experienceArray = (JSONArray) JSONArray.parse(experienceJson);
                List<HbBodyDto> hbBodyDtoList = experienceArray.toJavaList(HbBodyDto.class);
                for (HbBodyDto hbBodyDto : hbBodyDtoList) {
                    if ( ! dutyExperiencesTitles.contains( hbBodyDto.getId() )) {
                        ScreenDutyExperience experience = new ScreenDutyExperience();
                        experience.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        experience.setCreateBy("system");
                        experience.setCreateTime(LocalDateTime.now());
                        experience.setUpdateBy("system");
                        experience.setUpdateTime(LocalDateTime.now());
                        experience.setTitle(hbBodyDto.getTitle());
                        experience.setSubmitStatus("1");
                        experience.setStatus("0");
                        experience.setCreatePerson("系统");
                        experience.setCustomName(screenDutyMaps.getCustomName());
                        experience.setCustomId(screenDutyMaps.getCustomCode());
                        experience.setUrl(zsScreenDutyMaps.getLsUrl()+hbBodyDto.getUrl());
                        BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(hbBodyDto.getSendDeptId());
                        if (baseDeptInfo!=null){
                            experience.setSendCustomID(baseDeptInfo.getCustomId());
                        }
                        experience.setSendDeptID(hbBodyDto.getSendDeptId());
                        experience.setSendDeptName(hbBodyDto.getSendDeptName());
                        experience.setExperienceTime(LocalDate.now());
                        experience.setHbId(hbBodyDto.getId());
                        experience.setHbSendTime(hbBodyDto.getSendTime());
                        screenDutyExperiences.add(experience);
                    }
                }

                //值班信息
                HbDto hbDtoMessage = new HbDto();
                hbDtoMessage.setCustomsCode(screenDutyMaps.getCustomNo());
                hbDtoMessage.setMediaTypeName("值班信息");
                hbDtoMessage.setSendTime(timeFormatter.format(localDateTime));
                HttpEntity<HbDto> messageEntity = new HttpEntity<>(hbDtoMessage, headers);
                log.info("进行接口调用地址"+screenDutyMaps.getHbUrl());
                log.info("进行接口调用参数"+messageEntity);
                ResponseEntity<String> messageResponse = restTemplate.exchange(screenDutyMaps.getHbUrl(),
                        HttpMethod.POST, messageEntity, String.class);
                log.info("进行接口调用返回"+messageResponse);
                //将json转为对象
                String messageJson = messageResponse.getBody();
                log.info( "值班信息body{}" ,  messageJson );
                JSONArray messageArray = (JSONArray) JSONArray.parse(messageJson);
                log.info( "值班信息转json后body{}" ,  messageArray );
                List<HbBodyDto> hbBodyDtos = messageArray.toJavaList(HbBodyDto.class);
                log.info( "值班信息转List后{}" ,  hbBodyDtos );

                for (HbBodyDto hbBodyDto : hbBodyDtos) {
                    if (  !dutyMessagesTitles.contains( hbBodyDto.getId() )) {
                        log.info( "值班信息dto实体数据{}" ,  hbBodyDto );
                        ScreenDutyMessage message = new ScreenDutyMessage();
                        message.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        message.setCreateBy("system");
                        message.setCreateTime(LocalDateTime.now());
                        message.setUpdateBy("system");
                        message.setUpdateTime(LocalDateTime.now());
                        message.setStatus("0");
                        message.setTitle(hbBodyDto.getTitle());
                        message.setCreatePerson("系统");
                        message.setUrl(zsScreenDutyMaps.getLsUrl()+hbBodyDto.getUrl());
                        message.setCustomName(screenDutyMaps.getCustomName());
                        message.setCustomId(screenDutyMaps.getCustomCode());
                        BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(hbBodyDto.getSendDeptId());
                        if (baseDeptInfo!=null){
                            message.setSendCustomID(baseDeptInfo.getCustomId());
                        }
                        message.setSendDeptID(hbBodyDto.getSendDeptId());
                        message.setSendDeptName(hbBodyDto.getSendDeptName());
                        message.setHbId(hbBodyDto.getId());
                        message.setHbSendTime(hbBodyDto.getSendTime());
                        screenDutyMessages.add(message);
                        log.info( "值班信息实体数据{}" ,  message );
                        log.info( "sendAllZS执行");
                        sendAllZS(message);
                        log.info( "sendAllZS执行结束");
                    }
                }
            }
            log.info( "值班信息保存集合数据{}" ,  screenDutyMessages );
            List<ScreenDutyMessage> screenDutyMessageList = screenDutyMessages.stream().collect( Collectors.collectingAndThen(
                    Collectors.toCollection( () -> new TreeSet<ScreenDutyMessage>( Comparator.comparing( ScreenDutyMessage::getTitle )) ) , ArrayList::new
            ));
            List<ScreenDutyExperience> screenDutyExperienceList = screenDutyExperiences.stream().collect( Collectors.collectingAndThen(
                    Collectors.toCollection( () -> new TreeSet<ScreenDutyExperience>( Comparator.comparing( ScreenDutyExperience::getTitle )) ) , ArrayList::new
            ));
            log.info( "值班信息保存集合去重后数据{}" ,  screenDutyMessageList );
            screenDutyMessageRepository.saveBatch(screenDutyMessageList);
            screenDutyExperienceRepository.saveBatch(screenDutyExperienceList);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            log.info("获取hb数据失败", e);
            return ReturnT.FAIL;
        }
    }

    @XxlJob("tempRid")
    public ReturnT<String> tempRid(String param) {
        List<DutyScheduleInfo> students=dutyScheduleInfoRepository.list();
        List<DutySignInfo> dutySignInfos=new ArrayList<>();
        for (DutyScheduleInfo scheduleInfo:students){
            DutySignInfo info = dutySignInfoRepository.getOne(new LambdaQueryWrapper<DutySignInfo>()
                    .eq(DutySignInfo::getDId,scheduleInfo.getId()),false);
            if (info==null) {
                if (!org.apache.commons.lang.StringUtils.isEmpty(scheduleInfo.getDUserno())) {
                    DutySignInfo dutySignInfo = new DutySignInfo();
                    dutySignInfo.setDId(scheduleInfo.getId());
                    dutySignInfo.setCreateBy("sys");
                    dutySignInfo.setCreateTime(LocalDateTime.now());
                    dutySignInfo.setUpdateBy("sys");
                    dutySignInfo.setUpdateTime(LocalDateTime.now());
                    dutySignInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                    dutySignInfos.add(dutySignInfo);
                }
            }
        }
        if (!CollectionUtils.isEmpty(dutySignInfos)){
            dutySignInfoRepository.saveBatch(dutySignInfos);
        }
        return ReturnT.SUCCESS;

    }

    @XxlJob("HB2012")
    public ReturnT<String> HB2012(String param) {
        List<ScreenDutyMaps> screenDutyMaps=screenDutyMapsRepository.list();
        for (ScreenDutyMaps map:screenDutyMaps) {
            try {
                String url = map.getHbUrl();
                if (!StringUtils.isEmpty(url)&&!StringUtils.isEmpty(map.getHbMediaTypeMessage())) {
                    RestTemplate restTemplate = new RestTemplate();
                    JSONObject paramJSON = new JSONObject();
                    paramJSON.put("customsCode", map.getCustomCode());
                    paramJSON.put("mediaTypeName", map.getHbMediaTypeMessage());
                    paramJSON.put("sendTime", LocalDate.now().format(DateTimeFormatter.ISO_DATE));
//                    paramJSON.put("sendTime","2024-05-09");
                    paramJSON.put("maxCount", 10000);
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity entity = new HttpEntity(paramJSON, headers);
                    log.info("关区"+map.getCustomName()+"hb2012调用信息,地址"+url);
                    log.info("关区"+map.getCustomName()+"hb2012调用信息,参数"+paramJSON);
                    JSONArray resultArray=restTemplate.postForObject(url, entity, JSONArray.class) ;
                    log.info("关区"+map.getCustomName()+"hb2012调用信息,返回"+resultArray);
                    ScreenDutyMessage screenDutyMessage=new ScreenDutyMessage();
                    for (int i=0;i<resultArray.size();i++) {
                        JSONObject result=resultArray.getJSONObject(i);
                        String id = result.getString("id");
                        String title = result.getString("title");
                        String messageUrl = result.getString("url");
                        String sendDeptId = result.getString("sendDeptId");
                        String sendDeptName = result.getString("sendDeptName");
                        screenDutyMessage.setUrl(messageUrl);
                        screenDutyMessage.setId(id);
                        screenDutyMessage.setTitle(title);
                        if (!StringUtils.isEmpty(sendDeptName) && sendDeptName.contains("海关")){
                            BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(sendDeptId);
                            if (baseDeptInfo!=null){
                                screenDutyMessage.setSendCustomID(baseDeptInfo.getCustomId());
                            }
                            screenDutyMessage.setSendDeptID(sendDeptId);
                        }else {
                            screenDutyMessage.setSendDeptID(map.getCustomCode());
                            screenDutyMessage.setSendCustomID(map.getCustomCode());
                        }

                            screenDutyMessage.setSendDeptName(sendDeptName);
                        screenDutyMessage.setCustomId(map.getCustomCode());
                        screenDutyMessage.setCustomName(map.getCustomName());
                        screenDutyMessage.setCreatePerson("hb拉取");
                        screenDutyMessage.setCreateTime(LocalDateTime.now());
                        screenDutyMessage.setCreateBy("sys");
                        screenDutyMessage.setUpdateBy("sys");
                        screenDutyMessage.setUpdateTime(LocalDateTime.now());
                        screenDutyMessageRepository.saveOrUpdate(screenDutyMessage);
                        if ( screenDutyMessage.getSendDeptID()!=null&&screenDutyMessage.getSendDeptID().equals(map.getCustomCode())){
                            sendAllZS(screenDutyMessage);
                        }
                    }
                     paramJSON = new JSONObject();
                    paramJSON.put("customsCode", map.getCustomCode());
                    paramJSON.put("mediaTypeName", map.getHbMediaTypeMessageExperience());
                    paramJSON.put("sendTime", LocalDate.now().format(DateTimeFormatter.ISO_DATE));
                    paramJSON.put("maxCount", 10000);
                     headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                     entity = new HttpEntity(paramJSON, headers);
                    log.info("关区"+map.getCustomName()+"hb2012调用经验,地址"+url);
                    log.info("关区"+map.getCustomName()+"hb2012调用经验,参数"+paramJSON);
                     resultArray=restTemplate.postForObject(url, entity, JSONArray.class) ;
                    log.info("关区"+map.getCustomName()+"hb2012调用经验,返回"+resultArray);
                    ScreenDutyExperience screenDutyExperience=new ScreenDutyExperience();
                    for (int i=0;i<resultArray.size();i++) {
                        JSONObject result = resultArray.getJSONObject(i);
                        String id = result.getString("id");
                        String title = result.getString("title");
                        String messageUrl = result.getString("url");
                        String sendDeptId = result.getString("sendDeptId");
                        String sendDeptName = result.getString("sendDeptName");
                        screenDutyExperience.setUrl(messageUrl);
                        screenDutyExperience.setId(id);
                        screenDutyExperience.setTitle(title);
                        if (!StringUtils.isEmpty(sendDeptName) && sendDeptName.contains("海关")){
                            BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(sendDeptId);
                            if (baseDeptInfo!=null){
                                screenDutyMessage.setSendCustomID(baseDeptInfo.getCustomId());
                            }
                            screenDutyExperience.setSendDeptID(sendDeptId);
                        }else {
                            screenDutyExperience.setSendDeptID(map.getCustomCode());
                            screenDutyExperience.setSendCustomID(map.getCustomCode());
                        }
                        screenDutyExperience.setSendDeptName(sendDeptName);
                        screenDutyExperience.setCustomId(map.getCustomCode());
                        screenDutyExperience.setCustomName(map.getCustomName());
                        screenDutyExperience.setCreateTime(LocalDateTime.now());
                        screenDutyExperience.setCreatePerson("hb拉取");
                        screenDutyExperience.setCreateBy("sys");
                        screenDutyExperience.setUpdateBy("sys");
                        screenDutyExperience.setUpdateTime(LocalDateTime.now());
                        screenDutyExperienceRepository.saveOrUpdate(screenDutyExperience);
                    }
                }
            } catch (Exception e) {
                log.info("获取hb数据失败", e);
            }
        }
        return ReturnT.SUCCESS;
    }

    public void sendAllZS(ScreenDutyMessage message) {
        ScreenMessage screenMessage = new ScreenMessage();
        screenMessage.setCustomCode(message.getCustomId());
        screenMessage.setCustomName(message.getCustomName());
        screenMessage.setMessage(message.getTitle());
        screenMessage.setModule("MESSAGE_DUTY_MESSAGE");
        WebSocketSendInfoDTO webSocketSendInfoDTO = new WebSocketSendInfoDTO();
        webSocketSendInfoDTO.setMessage(message.getCustomName()+"报送1条值班信息，请及时查看！");
        webSocketSendInfoDTO.setScreenMessage(screenMessage);
        webSocketSendInfoDTO.setModule("MESSAGE_DUTY_MESSAGE");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<WebSocketSendInfoDTO> entity = new HttpEntity<>(webSocketSendInfoDTO, headers);
        restTemplate.exchange(systemConfig.getWebSocketSendInfoUrl() + "/sendAllZS", HttpMethod.POST, entity, String.class);
    }
//
//    public static void main(String[] args) {
//        try {
//            System.out.println(LocalDate.now().format(DateTimeFormatter.ISO_DATE));
//        } catch (Exception e) {
//            log.info("获取hb数据失败", e);
//        }
//    }
}
